package cn.edu.xjtu.carlWay.dpRepractice.maximumLengthOfRepeatedSubarray;

/**
 * @author Hydrion-QLz
 * @date 2022-05-04 11:01
 * @description https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray/
 * <p>
 * 718. 最长重复子数组
 * 给两个整数数组 nums1 和 nums2 ，返回 两个数组中 公共的 、长度最长的子数组的长度 。
 */
class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] arr = {1, 2, 3, 2, 1};
        int[] arr1 = {3, 2, 1, 4, 7};
        System.out.println(solution.findLength(arr, arr1));
    }

    public int findLength(int[] nums1, int[] nums2) {
        int n = nums1.length;
        int m = nums2.length;
        int[][] dp = new int[n + 1][m + 1];
        int ans = 0;
        
        for (int i = 1; i < n + 1; i++) {
            for (int j = 1; j < m + 1; j++) {
                if (nums1[i - 1] == nums2[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                    ans = Math.max(ans, dp[i][j]);
                }
            }
        }
        return ans;
    }
}